package cn.bone.mima.desaes;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AesCBCDemo2 {

    // AES的key必须是16个字节
    private static final String key = "1234567812345678";
    // AES CBC模式下，iv的长度也必须是16个字节
    private static final String initVector = "0123456789abcdef";
    private static final String transformation = "AES/CBC/PKCS5Padding";
    private static final String algorithm = "AES";

    public static void main(String[] args) throws Exception {
        // 原文
        String input = "123武汉的天气有点热啊";
        String encrypt = encrypt(input);
        System.out.println(encrypt);
        String decrypt = decrypt(encrypt);
        System.out.println(decrypt);
    }

    public static String encrypt(String input) throws Exception{

        SecretKey secretKey = new SecretKeySpec(key.getBytes("UTF-8"), algorithm);
        IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
        // 创建加密对象
        Cipher cipher = Cipher.getInstance(transformation);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        // 调用加密方法
        // 参数表示原文的字节数组
        byte[] bytes = cipher.doFinal(input.getBytes("UTF-8"));
        
        // 使用base64编码
        byte[] encode = Base64.getEncoder().encode(bytes);
        String s = new String(encode, "UTF-8");
        return s;
    }

    public static String decrypt(String input) throws Exception{

        SecretKey secretKey = new SecretKeySpec(key.getBytes("UTF-8"), algorithm);
        IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
        // 创建加密对象
        Cipher cipher = Cipher.getInstance(transformation);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);

        byte[] decode = Base64.getDecoder().decode(input.getBytes("UTF-8"));
        // 调用解密方法
        // 参数表示密文的字节数组
        byte[] bytes = cipher.doFinal(decode);
        String result = new String(bytes);
        return result;
    }
}
